{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Building a Lead Scoring Model with EvalML\n",
    "\n",
    "In this demo, we will build an optimized lead scoring model using EvalML. To optimize the pipeline, we will set up an objective function to maximize the revenue generated with true positives while taking into account the cost of false positives. At the end of this demo, we also show you how introducing the right objective during the training is significantly better than using a generic machine learning metric like AUC."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import evalml\n",
    "from evalml import AutoMLSearch\n",
    "from evalml.objectives import LeadScoring"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configure LeadScoring \n",
    "\n",
    "To optimize the pipelines toward the specific business needs of this model, you can set your own assumptions for how much value is gained through true positives and the cost associated with false positives. These parameters are\n",
    "\n",
    "* `true_positive` - dollar amount to be gained with a successful lead\n",
    "* `false_positive` - dollar amount to be lost with an unsuccessful lead\n",
    "\n",
    "Using these parameters, EvalML builds a pileline that will maximize the amount of revenue per lead generated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lead_scoring_objective = LeadScoring(true_positives=100, false_positives=-5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset\n",
    "\n",
    "We will be utilizing a dataset detailing a customer's job, country, state, zip, online action, the dollar amount of that action and whether they were a successful lead."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from urllib.request import urlopen\n",
    "import pandas as pd\n",
    "import woodwork as ww\n",
    "\n",
    "customers_data = urlopen(\n",
    "    \"https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/customers.csv\"\n",
    ")\n",
    "interactions_data = urlopen(\n",
    "    \"https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/interactions.csv\"\n",
    ")\n",
    "leads_data = urlopen(\n",
    "    \"https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/previous_leads.csv\"\n",
    ")\n",
    "customers = pd.read_csv(customers_data)\n",
    "interactions = pd.read_csv(interactions_data)\n",
    "leads = pd.read_csv(leads_data)\n",
    "\n",
    "X = customers.merge(interactions, on=\"customer_id\").merge(leads, on=\"customer_id\")\n",
    "y = X[\"label\"]\n",
    "X = X.drop(\n",
    "    [\n",
    "        \"customer_id\",\n",
    "        \"date_registered\",\n",
    "        \"birthday\",\n",
    "        \"phone\",\n",
    "        \"email\",\n",
    "        \"owner\",\n",
    "        \"company\",\n",
    "        \"id\",\n",
    "        \"time_x\",\n",
    "        \"session\",\n",
    "        \"referrer\",\n",
    "        \"time_y\",\n",
    "        \"label\",\n",
    "        \"country\",\n",
    "    ],\n",
    "    axis=1,\n",
    ")\n",
    "display(X.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will convert our data into Woodwork data structures. Doing so enables us to have more control over the types passed to and inferred by AutoML."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X.ww.init(semantic_tags={\"job\": \"category\"}, logical_types={\"job\": \"Categorical\"})\n",
    "y = ww.init_series(y)\n",
    "X.ww"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Search for the best pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to validate the results of the pipeline creation and optimization process, we will save some of our data as a holdout set."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "EvalML natively supports one-hot encoding and imputation so the above `NaN` and categorical values will be taken care of."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(\n",
    "    X, y, problem_type=\"binary\", test_size=0.2, random_seed=0\n",
    ")\n",
    "\n",
    "X.ww"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because the lead scoring labels are binary, we will use set the problem type to \"binary\". When we call `.search()`, the search for the best pipeline will begin. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl = AutoMLSearch(\n",
    "    X_train=X_train,\n",
    "    y_train=y_train,\n",
    "    problem_type=\"binary\",\n",
    "    objective=lead_scoring_objective,\n",
    "    additional_objectives=[\"auc\"],\n",
    "    allowed_model_families=[\"extra_trees\", \"linear_model\"],\n",
    "    max_batches=2,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "automl.search(interactive_plot=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### View rankings and select pipeline\n",
    "\n",
    "Once the fitting process is done, we can see all of the pipelines that were searched, ranked by their score on the lead scoring objective we defined."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl.rankings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To select the best pipeline we can call `automl.best_pipeline`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline = automl.best_pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Describe pipeline\n",
    "\n",
    "You can get more details about any pipeline, including how it performed on other objective functions by calling `.describe_pipeline()` and specifying the `id` of the pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl.describe_pipeline(automl.rankings.iloc[0][\"id\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on hold out\n",
    "\n",
    "Finally, since the best pipeline was trained on all of the training data, we evaluate it on the holdout dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline_score = best_pipeline.score(\n",
    "    X_holdout, y_holdout, objectives=[\"auc\", lead_scoring_objective]\n",
    ")\n",
    "best_pipeline_score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why optimize for a problem-specific objective?\n",
    "\n",
    "To demonstrate the importance of optimizing for the right objective, let's search for another pipeline using AUC, a common machine learning metric. After that, we will score the holdout data using the lead scoring objective to see how the best pipelines compare."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl_auc = evalml.AutoMLSearch(\n",
    "    X_train=X_train,\n",
    "    y_train=y_train,\n",
    "    problem_type=\"binary\",\n",
    "    objective=\"auc\",\n",
    "    additional_objectives=[lead_scoring_objective],\n",
    "    allowed_model_families=[\"extra_trees\", \"linear_model\"],\n",
    "    max_batches=2,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "automl_auc.search(interactive_plot=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl_auc.rankings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like before, we can look at the rankings and pick the best pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline_auc = automl_auc.best_pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the AUC and lead scoring score on holdout data\n",
    "best_pipeline_auc_score = best_pipeline_auc.score(\n",
    "    X_holdout, y_holdout, objectives=[\"auc\", lead_scoring_objective]\n",
    ")\n",
    "best_pipeline_auc_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert best_pipeline_score[\"Lead Scoring\"] >= best_pipeline_auc_score[\"Lead Scoring\"]\n",
    "assert best_pipeline_auc_score[\"Lead Scoring\"] >= 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we optimize for AUC, we can see that the AUC score from this pipeline is similar to the AUC score from the pipeline optimized for lead scoring. However, the revenue per lead is much smaller per lead when optimized for AUC and was much larger when optimized for lead scoring. As a result, we would have a huge gain on the amount of revenue if we optimized for lead scoring.\n",
    "\n",
    "This happens because optimizing for AUC does not take into account the user-specified `true_positive` (dollar amount to be gained with a successful lead) and `false_positive` (dollar amount to be lost with an unsuccessful lead) values. Thus, the best pipelines may produce the highest AUC but may not actually generate the most revenue through lead scoring.\n",
    "\n",
    "This example highlights how performance in the real world can diverge greatly from machine learning metrics."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
